# coding: utf-8

from datetime import date

from exts import db
from server.apps.trade_day.models import DayOpen

DATEFORMT = "%Y-%m-%d"


class TradeDay(object):
    @staticmethod
    def get_last_trade_day(last_day: date = None):
        """
        获取最后一个交易日 到截止日期的最后一个交易日
        :param last_day: 截止日期
        :return: 截止日期前的最后一个交易日
        """
        if not last_day:
            last_day = date.today()
        # 先检查交易日期是否完整，不完整，则错误
        result = DayOpen.query.filter(DayOpen.day == last_day).first()
        if result is None:
            raise Exception("数据库交易日不完整，请维护交易日数据")

        # 取数并返回
        sql = "select max(day) as date from day_open where day <= :day and is_open = 1"
        result = db.session.execute(sql, {"day": last_day}).fetchone()
        return result[0]

    @staticmethod
    def get_next_trade_day(last_day: date = None):
        """
        获取下一个交易日
        :param last_day:
        :return:
        """
        if not last_day:
            last_day = date.today()
        # 取数并返回
        sql = "select min(day) as date from day_open where day > :day and is_open = 1"
        result = db.session.execute(sql, {"day": last_day}).fetchone()
        return result[0]
